package com.project.les;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.ListActivity;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Toast;

import com.project.les.view.adapters.FeriadoListAdapter;
import com.project.les.view.elements.FeriadoViewElement;
import com.project.les.view.elements.OrdenaFeriados;

public class FeriadaoListActivity extends ListActivity implements TextWatcher {

	protected String locateName;
	protected String stateName;
	private AutoCompleteTextView myAutoComplete;
	private Map<String, String> mapCities = new HashMap<String, String>();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.tabs_search);

		String item[] = getLocais();

		myAutoComplete = (AutoCompleteTextView) findViewById(R.id.myautocomplete);
		myAutoComplete.addTextChangedListener(this);
		myAutoComplete.setAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_dropdown_item_1line, item));

		myAutoComplete.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				String[] listLocates = myAutoComplete.getText().toString()
						.split("-");
				locateName = listLocates[0].trim();
				stateName = mapCities.get(locateName);
				// Log.v("CURSOR",finish);
				List<FeriadoViewElement> dataFeriadoes = getFeriadoes(getAllFeriados(
						locateName, stateName));
				List<FeriadoViewElement> dataAllFeriados = getAllFeriados(
						locateName, stateName);
				// showToast(locateName + " * " + stateName + " ** " +
				// dataAllFeriados.size());
				Collections.sort(dataAllFeriados, new OrdenaFeriados());
				setAdapter(dataAllFeriados, dataFeriadoes);
			}
		});

		ListView lv = getListView();
		lv.setTextFilterEnabled(true);

		// this.showToast("Ainda não integrado");
	}

	protected void setAdapter(List<FeriadoViewElement> feriados,
			List<FeriadoViewElement> feriadoes) {
		setListAdapter(new FeriadoListAdapter(this, feriados, feriadoes));
	}

	private void showToast(String messageStr) {
		Toast msg = Toast.makeText(this, messageStr, Toast.LENGTH_SHORT);
		msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2,
				msg.getYOffset() / 2);
		msg.show();
	}

	private List<FeriadoViewElement> getFeriadoes(List<FeriadoViewElement> data) {
		List<FeriadoViewElement> feriadoes = new ArrayList<FeriadoViewElement>();
		int sentinela = 0;
		GregorianCalendar currentCalendar = new GregorianCalendar();

		for (int i = 0; i < data.size(); i++) {
			int day = data.get(i).getDate().get(Calendar.DAY_OF_WEEK);
			if (day == 6 && i != 0) {
				FeriadoViewElement temp = data.get(i);
				//if (currentCalendar.compareTo(temp.getDate()) < 0) {
				//	int missing_days = temp.getDate().get(Calendar.DAY_OF_YEAR)
				//			- currentCalendar.get(Calendar.DAY_OF_YEAR);
					// temp.setDescription(temp.getDescription() + "\n"
					// + "Faltam " + missing_days + " dias");
				//}
				feriadoes.add(temp);
				int after_day = data.get(i - 1).getDate()
						.get(Calendar.DAY_OF_WEEK);
				while (i != 0 && after_day == day - 1 && i > sentinela) {
					feriadoes.add(data.get(i - 1));
					day = after_day;
					after_day = data.get(i - 1).getDate()
							.get(Calendar.DAY_OF_WEEK);
				}
				sentinela = i;
			} else if (day == 2) {
				feriadoes.add(data.get(i));
			}
		}
		return feriadoes;
	}

	private List<FeriadoViewElement> getAllFeriados(String city, String state) {
		List<FeriadoViewElement> data1 = DataHelper.getInstance().selectAll(
				"isNacional = 1");
		List<FeriadoViewElement> data2 = getStateFeriados(state);
		List<FeriadoViewElement> data3 = DataHelper.getInstance().selectAll(
				"city LIKE '%" + city + "%'");
		data1.addAll(data2);
		data1.addAll(data3);
		return data1;
	}

	private List<FeriadoViewElement> getStateFeriados(String state) {
		List<FeriadoViewElement> data = DataHelper.getInstance().selectAll(
				"isState = 1", "state ASC, year, month, day");
		List<FeriadoViewElement> selectedState = new ArrayList<FeriadoViewElement>();
		for (int i = 0; i < data.size(); i++) {
			if (data.get(i).getState().equals(state)) {
				selectedState.add(data.get(i));
			}
		}
		return selectedState;
	}

	public void afterTextChanged(Editable arg0) {
		// TODO Auto-generated method stub

	}

	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub

	}

	private String[] getLocais() {
		AssetManager assetManager = getAssets();
		InputStream stream = null;
		List<String> listCities = new ArrayList<String>();
		try {
			String[] listStates = assetManager.list("municipal");
			for (int i = 0; i < listStates.length; i++) {
				stream = assetManager.open("municipal/" + listStates[i]);
				BufferedReader buffreader = new BufferedReader(
						new InputStreamReader(stream));
				String line;
				String city = "";
				while ((line = buffreader.readLine()) != null) {
					if (!line.contains("-") && line.trim().length() != 0) {
						city = line;
						listCities.add(city
								+ " - "
								+ listStates[i].substring(0,
										listStates[i].length() - 4));
						mapCities.put(
								city,
								listStates[i].substring(0,
										listStates[i].length() - 4));
					}
				}
				buffreader.close();
				stream.close();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

		String[] arrayCities = new String[listCities.size()];
		for (int i = 0; i < listCities.size(); i++) {
			arrayCities[i] = listCities.get(i);
		}
		return arrayCities;
	}

}
